import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class DormitoryUpdater:
    def __init__(self):
        self.db = Database()
    
    def update_dormitory(self, dormitory_id, capacity=None, status=None):
        """
        更新宿舍信息
        
        参数:
            dormitory_id (int): 宿舍ID
            capacity (int, optional): 新的容量
            status (str, optional): 新的状态
        
        返回:
            bool: 更新成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not dormitory_id:
                print("错误：宿舍ID必须提供")
                return False
            
            if capacity is not None:
                try:
                    capacity = int(capacity)
                    if capacity <= 0:
                        print("错误：容量必须是正整数")
                        return False
                except ValueError:
                    print("错误：容量必须是数字")
                    return False
            
            if status is not None and status not in ['available', 'unavailable', 'maintenance']:
                print("错误：状态必须是 'available', 'unavailable' 或 'maintenance'")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查宿舍是否存在
            self.db.cursor.execute(
                "SELECT building, room_number, capacity, current_count, status FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            dormitory = self.db.cursor.fetchone()
            
            if not dormitory:
                print(f"错误：ID为 {dormitory_id} 的宿舍不存在")
                return False
            
            building, room_number, old_capacity, current_count, old_status = dormitory
            
            # 检查新容量是否小于当前人数
            if capacity is not None and capacity < current_count:
                print(f"错误：新容量 {capacity} 小于当前人数 {current_count}")
                return False
            
            # 构建更新语句
            update_fields = []
            params = []
            
            if capacity is not None:
                update_fields.append("capacity = ?")
                params.append(capacity)
            
            if status is not None:
                update_fields.append("status = ?")
                params.append(status)
            
            if not update_fields:
                print("没有提供需要更新的字段")
                return False
            
            # 执行更新
            query = f"UPDATE dormitory SET {', '.join(update_fields)} WHERE id = ?"
            params.append(dormitory_id)
            
            self.db.cursor.execute(query, params)
            self.db.conn.commit()
            
            # 获取更新后的信息
            self.db.cursor.execute(
                "SELECT capacity, status FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            new_info = self.db.cursor.fetchone()
            new_capacity, new_status = new_info
            
            print(f"成功：宿舍 {building}-{room_number} 信息已更新")
            if capacity is not None:
                print(f"  容量: {old_capacity} -> {new_capacity}")
            if status is not None:
                print(f"  状态: {old_status} -> {new_status}")
            
            return True
        except Exception as e:
            print(f"错误：更新宿舍信息时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    updater = DormitoryUpdater()
    
    print("===== 宿舍信息更新 =====")
    
    # 先查询所有宿舍
    from query_dormitory import DormitoryQuery
    query = DormitoryQuery()
    dormitories = query.query_all_dormitories()
    
    if not dormitories:
        print("没有找到任何宿舍信息")
    else:
        print("\n宿舍ID\t楼号\t房间号\t容量\t当前人数\t状态")
        for dorm in dormitories:
            print(f"{dorm[0]}\t{dorm[1]}\t{dorm[2]}\t{dorm[3]}\t{dorm[4]}\t\t{dorm[5]}")
        
        dormitory_id = input("\n请输入要更新的宿舍ID: ")
        try:
            dormitory_id = int(dormitory_id)
            
            print("\n请选择要更新的信息（不更新的项目请留空）:")
            capacity = input("新容量: ")
            
            print("\n状态选项:")
            print("1. available - 可用")
            print("2. unavailable - 不可用")
            print("3. maintenance - 维护中")
            status_choice = input("新状态 (1-3): ")
            
            status = None
            if status_choice == '1':
                status = 'available'
            elif status_choice == '2':
                status = 'unavailable'
            elif status_choice == '3':
                status = 'maintenance'
            elif status_choice:
                print("错误：无效的状态选择")
            
            if capacity or status:
                updater.update_dormitory(dormitory_id, capacity, status)
            else:
                print("没有提供任何更新信息")
                
        except ValueError:
            print("错误：宿舍ID必须是数字")